package attendance

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/attendance"
	attendanceReq "github.com/flipped-aurora/gin-vue-admin/server/model/attendance/request"
)

type ClassService struct {
}

// CreateClass 创建班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) CreateClass(class *attendance.Class) (err error) {
	err = global.GVA_DB.Create(class).Error
	return err
}

// DeleteClass 删除班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) DeleteClass(ID string) (err error) {
	err = global.GVA_DB.Delete(&attendance.Class{}, "id = ?", ID).Error
	return err
}

// DeleteClassByIds 批量删除班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) DeleteClassByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]attendance.Class{}, "id in ?", IDs).Error
	return err
}

// UpdateClass 更新班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) UpdateClass(class attendance.Class) (err error) {
	err = global.GVA_DB.Model(&attendance.Class{}).Where("id = ?", class.ID).Updates(&class).Error
	return err
}

// GetClass 根据ID获取班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) GetClass(ID string) (class attendance.Class, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&class).Error
	return
}

// GetClassInfoList 分页获取班级记录
// Author [piexlmax](https://github.com/piexlmax)
func (classService *ClassService) GetClassInfoList(info attendanceReq.ClassSearch, belongTo uint) (list []attendance.Class, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&attendance.Class{})
	db = db.Where("belong_to = ?", belongTo)
	var classs []attendance.Class
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Classid != "" {
		db = db.Where("class_id = ?", info.Classid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&classs).Error
	return classs, total, err
}
